<template>
  <div class="create-post-container">
    <div class="header">
      <button @click="$router.go(-1)" class="back-btn">取消</button>
      <h2>发布笔记</h2>
      <button @click="submitPost" class="publish-btn">发布</button>
    </div>

    <div class="post-editor">
      <!-- 多张图片上传区域 -->
      <div class="image-upload-section">
        <div class="image-grid">
          <!-- 已上传的图片预览 -->
          <div v-for="(url, index) in imageUrls" :key="index" class="image-item">
            <img :src="$http.defaults.baseURL + url" class="preview-image">
            <button @click="removeImage(index)" class="remove-btn">×</button>
          </div>
          
          <!-- 添加图片按钮 -->
          <div v-if="imageUrls.length < 9" class="add-image-btn" @click="triggerFileInput">
            <input ref="fileInput" type="file" accept="image/*" multiple
                   @change="handleImageUpload" style="display:none">
            <span class="add-icon">+</span>
            <span class="add-text">{{ imageUrls.length > 0 ? '添加图片' : '添加封面' }}</span>
            <span class="image-count">{{ imageUrls.length }}/9</span>
          </div>
        </div>
      </div>

      <div class="post-content">
        <input v-model="title" placeholder="添加标题" class="title-input">
        <textarea v-model="content" placeholder="记录你的生活..."
                  class="content-textarea"></textarea>
        
        <!-- 标签输入区域 -->
        <div class="tags-section">
          <div class="tags-header">
            <span class="tags-label">添加标签（每行一个）</span>
            <span class="tags-count">{{ tags.length }}/10</span>
          </div>
          <textarea 
            v-model="tagsInput" 
            placeholder="输入标签，每个标签一行&#10;例如：&#10;美食&#10;旅行&#10;摄影"
            class="tags-textarea"
            @input="handleTagsInput"
          ></textarea>
          <div class="tags-preview" v-if="tags.length > 0">
            <span v-for="(tag, index) in tags" :key="index" class="tag-item">
              #{{ tag }}
              <button @click="removeTag(index)" class="remove-tag">×</button>
            </span>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      title: '',
      content: '',
      imageUrls: [],   // 存储多张图片的URL数组
      uploadFiles: [],  // 存储上传的文件对象
      isUploading: false,  // 上传状态
      tagsInput: '',   // 标签输入文本
      tags: []         // 解析后的标签数组
    }
  },
  methods: {
    triggerFileInput() {
      this.$refs.fileInput.click()
    },
    /* 选中文件后立即上传多张图片 */
    async handleImageUpload(e) {
      const files = Array.from(e.target.files)
      if (!files.length) return

      // 检查总图片数量限制
      if (this.imageUrls.length + files.length > 9) {
        alert('最多只能上传9张图片')
        return
      }

      this.isUploading = true

      try {
        // 并行上传所有选中的图片
        const uploadPromises = files.map(file => this.uploadSingleImage(file))
        const uploadedUrls = await Promise.all(uploadPromises)
        
        // 添加到图片数组
        this.imageUrls.push(...uploadedUrls)
        
        // 清空文件输入，允许重复选择相同文件
        this.$refs.fileInput.value = ''
        
      } catch (err) {
        console.error('图片上传失败', err)
        alert('部分图片上传失败，请重试')
      } finally {
        this.isUploading = false
      }
    },

    /* 上传单张图片 */
    async uploadSingleImage(file) {
      /* 简单校验 */
      if (!file.type.startsWith('image/')) {
        throw new Error('请选择图片文件')
      }

      const form = new FormData()
      form.append('file', file)

      const { data } = await this.$http.post('/api/upload', form, {
        headers: { 'Content-Type': 'multipart/form-data' }
      })
      
      // 返回相对路径，不包含baseURL，避免写死路径
      return data.url
    },

    /* 删除图片 */
    removeImage(index) {
      this.imageUrls.splice(index, 1)
    },

    /* 处理标签输入 */
    handleTagsInput() {
      // 按行分割并过滤空行
      const lines = this.tagsInput.split('\n').filter(line => line.trim() !== '')
      // 限制最多10个标签
      this.tags = lines.slice(0, 10).map(line => line.trim())
    },

    /* 删除标签 */
    removeTag(index) {
      this.tags.splice(index, 1)
      // 重新生成输入文本
      this.tagsInput = this.tags.join('\n')
    },

    /* 发布帖子 */
    async submitPost() {
      const token = localStorage.getItem('token')
      const username = localStorage.getItem('username')

      if (!token) {
        alert('请先登录')
        this.$router.push('/login')
        return
      }
      if (this.imageUrls.length === 0) {
        alert('请上传图片')
        return
      }

      try {
        await this.$http.post('/api/posts', {
          username,
          title: this.title,
          content: this.content,
          images: this.imageUrls,   // 传递多张图片URL数组
          tags: this.tags          // 传递标签数组
        })
        this.$router.push('/')
      } catch (error) {
        console.error('发布失败', error)
        alert('发布失败，请重试')
      }
    }
  }
}
</script>

<style scoped>
.create-post-container {
  max-width: 600px;
  margin: 0 auto;
  padding: 20px;
}
.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 0;
  border-bottom: 1px solid #eee;
}
.back-btn, .publish-btn {
  background: none;
  border: none;
  font-size: 16px;
  cursor: pointer;
}
.back-btn { color: #666; }
.publish-btn { color: #ff2449; font-weight: bold; }
.post-editor { margin-top: 20px; }

/* 多图片上传区域样式 */
.image-upload-section {
  margin-bottom: 20px;
}
.image-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 10px;
}
.image-item {
  position: relative;
  aspect-ratio: 1;
  border-radius: 8px;
  overflow: hidden;
  background: #f8f8f8;
}
.image-item .preview-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}
.remove-btn {
  position: absolute;
  top: 5px;
  right: 5px;
  width: 24px;
  height: 24px;
  background: rgba(0,0,0,0.6);
  color: white;
  border: none;
  border-radius: 50%;
  font-size: 18px;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
}
.remove-btn:hover {
  background: rgba(0,0,0,0.8);
}
.add-image-btn {
  aspect-ratio: 1;
  background: #f8f8f8;
  border: 2px dashed #ddd;
  border-radius: 8px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  cursor: pointer;
  transition: all 0.3s ease;
}
.add-image-btn:hover {
  border-color: #ff2449;
  background: #fff5f7;
}
.add-icon {
  font-size: 30px;
  color: #999;
  line-height: 1;
}
.add-text {
  font-size: 14px;
  color: #666;
  margin-top: 5px;
}
.image-count {
  font-size: 12px;
  color: #999;
  margin-top: 2px;
}

.post-content { margin-top: 20px; }
.title-input {
  width: 100%;
  padding: 15px 0;
  font-size: 18px;
  font-weight: bold;
  border: none;
  border-bottom: 1px solid #eee;
  margin-bottom: 15px;
}
.content-textarea {
  width: 100%;
  min-height: 150px;
  border: none;
  resize: none;
  font-size: 16px;
  line-height: 1.6;
}

/* 标签输入区域样式 */
.tags-section {
  margin-top: 20px;
  padding: 15px 0;
  border-top: 1px solid #eee;
}
.tags-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}
.tags-label {
  font-size: 14px;
  color: #333;
  font-weight: 500;
}
.tags-count {
  font-size: 12px;
  color: #999;
}
.tags-textarea {
  width: 100%;
  min-height: 80px;
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 8px;
  resize: vertical;
  font-size: 14px;
  line-height: 1.4;
}
.tags-textarea:focus {
  outline: none;
  border-color: #ff2449;
}
.tags-preview {
  margin-top: 10px;
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}
.tag-item {
  display: inline-flex;
  align-items: center;
  background: #fff5f7;
  color: #ff2449;
  padding: 4px 8px;
  border-radius: 12px;
  font-size: 12px;
  font-weight: 500;
}
.remove-tag {
  background: none;
  border: none;
  color: #ff2449;
  font-size: 14px;
  cursor: pointer;
  margin-left: 4px;
  padding: 0;
  width: 14px;
  height: 14px;
  display: flex;
  align-items: center;
  justify-content: center;
}
.remove-tag:hover {
  color: #d41e3c;
}

/* 响应式布局 */
@media (max-width: 480px) {
  .image-grid {
    grid-template-columns: repeat(2, 1fr);
  }
}
</style>